const { poolQuery } = require("../utils/db");
const utils = {
  arrToRouterTree(data) {
    const result = [];
    const map = new Map();

    data.forEach((el) => map.set(el.id, el));
    data.forEach((el) => {
      const parent = map.get(el.parent_id);
      if (parent) {
        (parent?.children ?? (parent.children = [])).push(el);
      } else {
        result.push(el);
      }
    });
    return result;
  },
  // 对单路由做特殊处理
  specialRouterTree(data) {
    const dataList = this.arrToRouterTree(data);
    return this.recursiveTree(dataList);
  },
  // 递归处理
  recursiveTree(data) {
    return (
      data?.map((item) => {
        let children = null;
        const length = item.children?.length ?? 0;
        if (length === 1) {
          item = item.children[0];
          children = this.recursiveTree(item.children);
        } else if (length > 1) {
          children = this.recursiveTree(item.children);
        }
        return {
          ...item,
          children,
        };
      }) ?? null
    );
  },
  checkSqlField(req, sql, field, tips = "库中含有重复的字段名") {
    return new Promise((resolve, reject) => {
      if (!field) {
        reject("参数传递方式有误，请检查");
      }
      poolQuery(sql, [req.body[field]], (err, rows) => {
        if (err) {
          reject(err);
        }
        switch (rows.length) {
          case 0: {
            break;
          }
          case 1: {
            // 如果id与body的id相同
            if (rows[0].id !== req.body.id) {
              reject(tips);
            }
            break;
          }
          default: {
            reject("数据库中存在重复数据，请联系开发人员排除");
            break;
          }
        }
        resolve();
      });
    });
  },
};
module.exports = utils;
